import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MapPoint, Camera } from '@/types'

export const useMapStore = defineStore('map', () => {
  // 状态
  const viewer = ref<any>(null) // vue-cesium的viewer类型
  const mapPoints = ref<MapPoint[]>([])
  const selectedPoint = ref<MapPoint | null>(null)
  const mapLoaded = ref(false)
  const mapLoading = ref(false)

  // 计算属性
  const cameraPoints = computed(() => 
    mapPoints.value.filter(point => point.type === 'camera')
  )

  /**
   * 初始化地图 (vue-cesium版本)
   */
  const initMap = (container: HTMLElement): Promise<any> => {
    return new Promise((resolve, reject) => {
      try {
        mapLoading.value = true
        
        // 注意：在vue-cesium中，地图初始化由VcViewer组件处理
        // 这里只是设置状态，实际的viewer会在onViewerReady中设置
        console.log('MapStore: 等待vue-cesium初始化...')
        
        mapLoaded.value = true
        mapLoading.value = false
        
        // 返回一个占位符，实际的viewer会在组件中设置
        resolve(null)
      } catch (error) {
        mapLoading.value = false
        reject(error)
      }
    })
  }

  /**
   * 销毁地图
   */
  const destroyMap = (): void => {
    if (viewer.value) {
      viewer.value.destroy()
      viewer.value = null
      mapLoaded.value = false
    }
  }

  /**
   * 添加地图点位 (vue-cesium版本)
   */
  const addMapPoint = (point: MapPoint): void => {
    if (!viewer.value) return

    // 在vue-cesium中，实体由VcEntity组件管理
    // 这里只是添加到状态中
    mapPoints.value.push(point)
  }

  /**
   * 批量添加地图点位
   */
  const addMapPoints = (points: MapPoint[]): void => {
    points.forEach(point => addMapPoint(point))
  }

  /**
   * 移除地图点位 (vue-cesium版本)
   */
  const removeMapPoint = (pointId: string): void => {
    const index = mapPoints.value.findIndex(p => p.id === pointId)
    if (index > -1) {
      mapPoints.value.splice(index, 1)
    }
  }

  /**
   * 清除所有点位 (vue-cesium版本)
   */
  const clearMapPoints = (): void => {
    mapPoints.value = []
  }

  /**
   * 飞行到指定点位 (vue-cesium版本)
   */
  const flyToPoint = (point: MapPoint, duration = 2.0): void => {
    if (!viewer.value) return

    // 使用vue-cesium的viewer
    const Cesium = (window as any).Cesium
    if (Cesium) {
      viewer.value.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          point.longitude,
          point.latitude,
          (point.height || 0) + 1000
        ),
        duration
      })
    }
  }

  /**
   * 设置地图视角 (vue-cesium版本)
   */
  const setView = (longitude: number, latitude: number, height = 10000): void => {
    if (!viewer.value) return

    const Cesium = (window as any).Cesium
    if (Cesium) {
      viewer.value.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
      })
    }
  }

  /**
   * 根据点位类型获取图标
   */
  const getPointIcon = (type: string): string => {
    const icons = {
      camera: '/icons/camera.png',
      building: '/icons/building.png',
      equipment: '/icons/equipment.png',
      alarm: '/icons/alarm.png'
    }
    return icons[type as keyof typeof icons] || icons.camera
  }

  /**
   * 加载摄像头数据到地图
   */
  const loadCamerasToMap = async (cameras: Camera[]): Promise<void> => {
    const points: MapPoint[] = cameras.map(camera => ({
      id: `camera_${camera.id}`,
      longitude: camera.longitude,
      latitude: camera.latitude,
      height: 0,
      name: camera.name,
      type: 'camera',
      data: camera
    }))

    clearMapPoints()
    addMapPoints(points)
  }

  /**
   * 获取地图截图
   */
  const getMapScreenshot = (): Promise<string> => {
    return new Promise((resolve) => {
      if (!viewer.value) return resolve('')
      
      viewer.value.render()
      const canvas = viewer.value.scene.canvas
      const dataUrl = canvas.toDataURL('image/png')
      resolve(dataUrl)
    })
  }

  return {
    // 状态
    viewer,
    mapPoints,
    selectedPoint,
    mapLoaded,
    mapLoading,
    
    // 计算属性
    cameraPoints,
    
    // 方法
    initMap,
    destroyMap,
    addMapPoint,
    addMapPoints,
    removeMapPoint,
    clearMapPoints,
    flyToPoint,
    setView,
    loadCamerasToMap,
    getMapScreenshot
  }
})